
  /**************************************************
   *                      Main
   **************************************************/


$(function(){
	var $map = $('#googleMap'), 
		menu = new Menu($map),
	
		current,  // current click event (used to save as start / end position)
		m1,       // marker "from"
		m2,       // marker "to"
		center = [39.925700, 32.845353],
		path = new google.maps.KmlLayer();

	
	// INITIALIZE GOOGLE MAP
	map = $map.gmap3(
	  {action: 'init',
	    options:{
	      center:center,
	      zoom: 12
	    },
	    events:{
	      rightclick:function(map, event){
	        current = event;
	        menu.open(current);
	      },
	      click: function(){
	        menu.close();
	      },
	      dragstart: function(){
	        menu.close();
	      },
	      zoom_changed: function(){
	        menu.close();
	      }
	    }
	  }
	);
	
	// update marker
	function updateMarker(marker, isM1){
		if (isM1){
			m1 = marker;
		} else {
			m2 = marker;
		}
		updateDirections();
	}
	
	// add marker and manage which one it is (A, B)
	function addMarker(isM1){
		// clear previous marker if set
		var clear = {action:'clear', name:'marker', tag:''};
		if (isM1 && m1) {
			clear.tag = 'from';
			$map.gmap3(clear);
		} else if (!isM1 && m2){
			clear.tag = 'to';
			$map.gmap3(clear);
		}
		// add marker and store it
		$map.gmap3({
			action:'addMarker',
			latLng:current.latLng,
			options:{
				draggable:true,
				icon:new google.maps.MarkerImage('http://maps.gstatic.com/mapfiles/icon_green' + (isM1 ? 'A' : 'B') + '.png')
			},
			tag: (isM1 ? 'from' : 'to'),
			events: {
				dragend: function(marker){
					updateMarker(marker, isM1);
				}
			},
			callback: function(marker){
				updateMarker(marker, isM1);
			}
		});
	}
	
    // function called to update route suggestion list if m1 and m2 are set
    function updateDirections(){
      if (!(m1 && m2)){
        return;
      }
      //data sent to direction.php for find possible routes for specified two points
      var data = 
		{
			"fromX": m1.getPosition().lat(),
			"fromY": m1.getPosition().lng(),
			"toX": m2.getPosition().lat(),
			"toY": m2.getPosition().lng()
		}

		var dataString = JSON.stringify(data);
		$.post('direction.php', {data: dataString}, showDirection, "text");
    }
    
        //adds marker for stop points with the given parameters
	function addStop(location, stopNo, locInfo, renk) {		
		$map.gmap3({
			action:'addMarker',
			latLng:location,
                        tag:'stop',
			options:{
				draggable:false,
				icon:new google.maps.MarkerImage('http://st07110364.etu.edu.tr/' + renk + '/number_' + stopNo + '.png', null, null, null, new google.maps.Size(25, 25))
			}
		});
	}
	
        //displays the path from kml file
	function showPath(filename){
                //this variable is used for google not to cache our kml file
                var rand = Math.floor(Math.random()*10000);
		$map.gmap3(
	        {action: 'addKmlLayer',
	          url: 'http://st07110364.etu.edu.tr/' + filename + '?id=' + rand,
                  tag:'stop',
	          options:{
	            suppressInfoWindows: true
	          }
	        }
	    );
	}
        //an ajax request is being done for getting the specified route info
    function hatGoster(istek, bilgi){
        var data = 
        {
            "istek":istek,
            "bilgi": bilgi
        }

        var dataString = JSON.stringify(data);
        $.post('goster.php', {
            data: dataString
        }, showHat, "text");
    }
	
        //if bolge combobox's value changes ana ajax request for populating the 'hat' combobox
	$('#bolge').change(function(){
		var data = 
		{
			"istek":"bolge",
			"bilgi": $('#bolge').val()
		}

		var dataString = JSON.stringify(data);
		$.post('goster.php', {data: dataString}, showBolge, "text");
	});
	
        //for full route info
	$('#hat').change(function(){
            hatGoster("hat", $('#hat').val());
	});
        
        //for partial route info
        $('#navcontainer a.tekOption').live('click',function(){
            hatGoster("hat", $(this).parent().data('data'));
        });
        
        //for partial route info with transfer
        $('#navcontainer a.ikiOption').live('click',function(){
            hatGoster("ikiHatGoster", $(this).parent().data('data'));
            //ikiHatGoster($(this).parent().data('data'));
        });
        
        //this is for marking the clicked route suggestion
        $('#navlist li').live('click',function(){
            $('#navlist li').removeClass();
            $(this).addClass('clicked');
        });
	
        //this function populates the 'hat' combobox
	function showBolge(res){
		var obj = JSON.parse(res);
		var hat;
		$('#hat').html('<option value="bos"> Bir Hat Seçin </option>');
		for(hat in obj){
			$('#hat').append('<option value="' + obj[hat].kod + '">(' + obj[hat].kod + ') - ' + obj[hat].adi + '</option>');
		}
	}
		 
        //this function displays the requested routes' information
	function showHat(res){
		var obj = JSON.parse(res);
		var stop;
		
		$map.gmap3({'action':'clear','name':['marker','kmllayer'],'tag':'stop'});
		
                //add marker for each stop point
		for(stop in obj['duraklar']){
			var location = new google.maps.LatLng(obj['duraklar'][stop].px,obj['duraklar'][stop].py);
                        //if the route is for a minibus then don't put markers
                        if(obj['duraklar'][stop].kod.substring(0,1) != 'D') {
                            addStop(location, obj['duraklar'][stop].sira, obj['duraklar'][stop].yeri, obj['duraklar'][stop].renk);
                        }
		}
                //display the kml file
		showPath("file.kml");
                //this is for second route if exists
                if (typeof obj['aaid'] != 'undefined') {
                    showPath("file2.kml");
                }
                
	}
	
        //this function is called when two points are specified and 
        //a respond has been taken from ajax request
	function showDirection(res){
		var obj = JSON.parse(res);
		$('#navlist').html("");
                //if there is no single route
                if(obj['tek'].length == 0) {
                    //if there is no two route
                    if(obj['iki'].length == 0) {
                        $('#hatUyari').html('Uygun tek veya aktarmalı hat bulunamadı!.');
                        $('#hatUyari').removeClass();
                        $('#hatUyari').addClass('error');
                    } else {
                        $('#hatUyari').html('Uygun tek hat bulunamadı. Aktarmalı hatlar gösteriliyor.');
                        $('#hatUyari').removeClass();
                        $('#hatUyari').addClass('info');
                        //populating the suggestion list for two routes
                        for(hat in obj['iki']){
                            var newOption = $("<li><a href='#' class='ikiOption'><span style='color:orange;'>" + obj['iki'][hat].akod + "</span><img class='rightArrow' src='images/right-arrow.png' />" +  obj['iki'][hat].bkod + "<div style='color:orange;'>"+ obj['iki'][hat].aadi +"</div><div style='margin-top:-10px; color:blue;'>"+ obj['iki'][hat].badi +"</div></a></li>");
                            newOption.data('data',obj['iki'][hat]);
                            newOption.appendTo("#navlist");
                        }
                    }
                } else {
                    $('#hatUyari').html('Seçilen noktalara uygun tek hatlar gösteriliyor.');
                    $('#hatUyari').removeClass();
                    $('#hatUyari').addClass('success');
                    //populating the suggestion list for single routes
                    for(hat in obj['tek']){
                        var newOption = $("<li><a href='#' class='tekOption'>" + obj['tek'][hat].kod + "<div>" + obj['tek'][hat].adi + "</div></a></li>");
                        newOption.data('data',obj['tek'][hat]);
                        newOption.appendTo("#navlist");			
                    }
                }
		
	}

	// MENU : ITEM 1
	menu.add('Hareket noktası', 'itemA', 
	  function(){
	    menu.close();
	    addMarker(true);
	  });
	
	// MENU : ITEM 2
	menu.add('Varış noktası', 'itemB separator', 
	  function(){
	    menu.close();
	    addMarker(false);
	  })
	
	// MENU : ITEM 3
	menu.add('Yaklaş', 'zoomIn', 
	  function(){
	    var map = $map.gmap3('get');
	    map.setZoom(map.getZoom() + 1);
	    menu.close();
	  });
	
	// MENU : ITEM 4
	menu.add('Uzaklaş', 'zoomOut',
	  function(){
	    var map = $map.gmap3('get');
	    map.setZoom(map.getZoom() - 1);
	    menu.close();
	  });
	
	// MENU : ITEM 5
	menu.add('Merkeze al', 'centerHere', 
	  function(){
	      $map.gmap3('get').setCenter(current.latLng);
	      menu.close();
	  });
});
